package models

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/driver/postgres"
	"sixiao.lcol.top/admin/common"
	"sixiao.lcol.top/admin/tools"
	"log"
	"time"
)

var DB *gorm.DB

type Model struct {
	ID        uint       `gorm:"primary_key" json:"id"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}

func init() {
	Connect()
}
func Connect() error {
	c4db := common.GetDbConf()
	if c4db == nil {
		panic("解析配置异常")
	}
	// dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", 
	// 				   c4db.Username, c4db.Password, c4db.Server, c4db.Port, c4db.Database)
	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai",
					    c4db.Server, c4db.Username, c4db.Password, c4db.Database, c4db.Port)
	var err error
	// DB, err = gorm.Open("mysql", dsn)
	DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Println(err)
		tools.Logger().Println(err)
		return err
		//panic("数据库连接失败!")
	}

	InitConfig()
	return nil
}
func Execute(sql string) error {
	return DB.Exec(sql).Error
}
